package com.example.bes014.multiple.ds.demo.config;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.mapping.MappedStatement;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;

@Intercepts({
    @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
    )
})
public class DataSourceLoggingInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取 MyBatis Executor 实例
        Executor executor = (Executor) invocation.getTarget();

        // 获取当前执行查询时的 Connection
        Connection connection = executor.getTransaction().getConnection();

        if (connection != null) {
            // 打印 DataSource 信息
            printDataSourceInfo(connection);
        } else {
            System.out.println("No connection found.");
        }

        // 执行查询
        return invocation.proceed();
    }

    private void printDataSourceInfo(Connection connection) {
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            String userName = metaData.getUserName();
            if ("bes@192.168.92.1".equals(userName)) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                for (StackTraceElement element : stackTrace) {
                    System.out.println(element);
                }
            }
        } catch (SQLException e) {
            System.err.println("Error while printing DataSource info: " + e.getMessage());
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可通过 properties 获取外部配置
    }
}
